/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.interceptor;

import com.lvyh.lightframe.job.admin.annotation.PermitLimit;
import com.lvyh.lightframe.job.admin.bean.JobUserBean;
import com.lvyh.lightframe.job.Constants;
import com.lvyh.lightframe.job.admin.service.UserLoginService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private UserLoginService userLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }

        if (userLoginService.checkExcludeUrl(request)) {
            return super.preHandle(request, response, handler);
        }

        boolean isAdmin = false;
        HandlerMethod method = (HandlerMethod) handler;
        PermitLimit permission = method.getMethodAnnotation(PermitLimit.class);
        if (permission != null) {
            isAdmin = permission.superAdmin();
        }
        JobUserBean loginUser = userLoginService.checkUserLogin(request);
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/toLogin");
            return false;
        }

        if (isAdmin && loginUser.getUserType() != 2) {
            throw new RuntimeException("no permission!");
        }
        request.setAttribute(Constants.USER_LOGIN_KEY, loginUser);
        request.getSession().setAttribute(Constants.SESSION_USER_INFO, loginUser);

        return super.preHandle(request, response, handler);
    }

}
